<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>练习5</title>
</head>

<body>

</body>
<script>
    //1.截取字符串"我爱中华人民共和国"，中的"中华"
    let str = "我爱中华人民共和国";
    let result = str.substring(2, 4);
    console.log(result);

    //2."abcoefoxyozzopp"查找字符串中所有o出现的位置
    let str1 = "abcoefoxyozzopp";
    let arr = [];
    let index = str1.indexOf('o');

    while (index != -1) {
        arr.push(index);
        index = str1.indexOf('o', index + 1);
    }
    console.log(arr);

    //3.把字符串中所有的o替换成!
    let str2 = "abcoefoxyozzopp";
    let newStr = str2.replace(/o/g, '!');
    console.log(newStr);

    //4.判断一个字符串中出现次数最多的字符，统计这个次数
    function find(str) {
        let charCount = {};

        for (let i = 0; i < str.length; i++) {
            let char = str.charAt(i);

            if (charCount[char]) {
                charCount[char]++;
            }
            else {
                charCount[char] = 1;
            }
        }

        let maxChar = '';
        let maxCount = 0;

        for (let char in charCount) {
            if (charCount[char] > maxCount) {
                maxCount = charCount[char];
                maxChar = char;
            }
        }

        return {
            char: maxChar,
            count: maxCount
        };
    }

    let result1 = find("abcoefoxyozzopp");
    console.log(`出现最多的字符是 "${result1.char}"，出现了 ${result1.count} 次`);
</script>

</html>